<template>
  <a-menu
    v-model:open-keys="openKeys"
    v-model:selected-keys="selectedKeys"
    :mode="mode"
    :theme="theme"
    @select="handleSelected"
  >
    <template v-for="item in menus">
      <sub-menu v-if="!item?.meta?.hidden" :info="item" />
    </template>
  </a-menu>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import SubMenu from './SubMenu.vue';
import type { RouterInterface } from '@/router/types';

/* 接收外部参数 */
interface PropsType {
  mode?: string;
  theme?: string;
  open?: boolean; // 是否展开选中项
  dataSource?: RouterInterface[]; // 路由
}
const props = withDefaults(defineProps<PropsType>(), {
  mode: 'horizontal',
  theme: 'light',
  open: false,
});

/* 高亮选择项 & 打开选中项 */
const route = useRoute();
const openKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
const setKeys = () => {
  selectedKeys.value = route.matched.slice(1, route.matched.length).map((item) => item.path);
  if (props.open) {
    openKeys.value = route.matched.slice(1, route.matched.length - 1).map((item) => item.path);
  } else {
    openKeys.value = [];
  }
};
watch(
  () => route,
  () => {
    setKeys();
  },
  {
    deep: true,
  }
);

/* 设置菜单列表 */
const menus = ref<RouterInterface[]>([]);
watch(
  () => props.dataSource,
  () => {
    menus.value = props.dataSource!;
    setKeys();
  },
  { immediate: true }
);

/* 点击跳转 */
const router = useRouter();
const handleSelected = (res: any) => {
  res && res.key ? router.push(res.key) : null;
};
</script>
